import config from '../config/env'
import { logout } from '../utils/wxFun'

let loadingCount = 0

export function isNeedHandle(code) {
    const codes = [
        '40001', // 没有登录信息
        '40002', // http 状态码不在 [200, 399] 范围内，或数据结构不是 json 字符串
        '40003', // 调用微信请求接口报错
        '40004', // 拦截多个需要登录的请求
    ]
    return !codes.includes(code)
}


// 过滤掉自定义参数
function filterParams(params) {
    const paramsKey = ['url', 'data', 'header', 'timeout', 'method', 'dataType', 'responseType', 'enableHttp2', 'enableQuic', 'enableCache']
    for (let key in params) {
        if (!paramsKey.includes(key)) {
            delete params[key]
        }
    }

}

function filterParams2(params) {
    if (typeof params == "object") {
        for (let key of Object.keys(params)) {
            if (params[key] == 'null') {
                params[key] = null;
            }
            else if (typeof params[key] == "object") {
                filterParams2(params[key]);
            }
        }

    }
}

function baseRequest(params) {
    const app = getApp()
    return new Promise((resolve, reject) => {
        if (params.needLogin && !app.globalData.isLogin) {
            logout()
            return reject({ frontCode: '40004' })
        }
        //url
        let url = config.api + params.url
        console.log(url, 'url')
        const hasLoading = params.hasLoading;
        if (hasLoading) {
            wx.$Fun.showLoading()
            loadingCount++
        }

        //jwt
        let token = ''
        try {
            token = wx.getStorageSync('token')
        } catch { }

        let header = {
            Authorization: token
        }
        if (params.header) {
            header = {
                ...header,
                ...params.header
            }
        }

        // 请求前把不需要的参数过滤掉
        filterParams(params)
        //filterParams2(params)

        //请求
        wx.request({
            timeout: 20000, // 超时时间默认为 10 秒
            ...params,
            header,
            url,
            success(res) {
                console.log('response=', res)
                // 没有登录
                if (res.statusCode === 401) {
                    // 清除登录信息
                    logout()
                    return reject({ frontCode: '40001' })
                }
                // 返回状态出错或者数据结构不对  || !wx.$util.isJson(res.data)
                else if (res.statusCode < 200 || res.statusCode >= 400) {
                    return reject({ frontCode: '40002' })
                }

                if (!res.data) return reject({ frontCode: '40002' })

                let data = res.data;

                return data.IsSuccess ? resolve(data) : reject(data)
            },
            fail() {
                reject({
                    frontCode: '40003'
                })
            },
            complete() {
                if (hasLoading) {
                    loadingCount--
                    if (loadingCount <= 0) {
                        wx.$Fun.hideLoading()
                        loadingCount = 0
                    }
                }
            }
        })
    })
}

export default baseRequest